package com.jule.miaozhuapc.controller;

import com.jule.miaozhuapc.ano.Auth;
import com.jule.miaozhuapc.ano.TokenUser;
import com.jule.miaozhuapc.domain.WawaUser;
import com.jule.miaozhuapc.dto.WsUtil;
import com.jule.miaozhuapc.service.PingPayService;
import com.jule.miaozhuapc.util.*;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping( value = Const.WAWA_HTTP_URL_V1+ "/wx")
public class WxPayController {
    @Autowired
    PingPayService pingPayService;

    private Logger logger = Logger.getLogger(WxPayController.class);

    @Auth
    @RequestMapping(value = "/wxpay", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public  @ResponseBody
    String  wxcodepay(
                          @RequestParam(name="payConfigId") String payConfigId,
                          @RequestParam(name="channel") String channel,
                          @TokenUser WawaUser user) throws  Exception{

        JSONObject rst = new JSONObject();
        JSONObject status = new JSONObject();

        // https://www.likewawa.com/miaozhuapc/v1/ping/createCharge?payConfigId=1&channel=
        WsUtil ws = new WsUtil();
        if ("".equals(payConfigId) || "".equals(channel)){
            status.put("code", "00000001");
            status.put("message", "error");
            return rst.put("status", status).toString();
        }
        Map<Object, Object> map = pingPayService.wxCharge(user, Long.parseLong(payConfigId), channel);

        logger.info(map);
        status.put("code", "00000000");
        status.put("message", "success");
        rst.put("status", status);
        rst.put("body", new JSONObject(map));

        logger.info(rst);
        return rst.toString();
    }


    /**
     *  帮助APP 服务器代充值  朋友代充
     * @param payConfigId
     * @param channel
     * @param s1UserId
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/s1/wxpay", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @Auth
    public  @ResponseBody
    String  S1wxcodepay(
            @RequestParam(name="payConfigId") Long s1PayConfigId,
            @RequestParam(name="channel") String channel,
            @RequestParam(name = "userId") Long s1UserId,
            @TokenUser WawaUser user) throws  Exception{

        logger.info("s1PayConfigId = " + s1PayConfigId + " / channel= "+channel + " /s1UserId=" +s1UserId);
        JSONObject rst = new JSONObject();
        JSONObject status = new JSONObject();

        // https://www.likewawa.com/miaozhuapc/v1/ping/createCharge?payConfigId=1&channel=
        WsUtil ws = new WsUtil();
        if ("".equals(s1PayConfigId) || "".equals(channel)){
            status.put("code", "00000001");
            status.put("message", "error");
            return rst.put("status", status).toString();
        }
        Map<Object, Object> map = pingPayService.wxS1Charge(user.getWxOpenId(), s1PayConfigId, channel, s1UserId);

        logger.info(map);
        status.put("code", "00000000");
        status.put("message", "success");
        rst.put("status", status);
        rst.put("body", new JSONObject(map));

        logger.info(rst);
        return rst.toString();
    }


    /**
     * 前端获取 Wx js SDK
     * @param url
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/get/js/sdk", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public @ResponseBody Map getjssdk(@RequestParam(name="url") String url,
                                         HttpServletRequest request,
                                         HttpServletResponse response)throws  Exception{
        String APPID = Const.WAWA_H5_WX_APPID;
        try {
            WxToken wxtoken = WxCommonUtil.getToken(APPID, Const.WAWA_H5_WX_SECRET);
            String token = wxtoken.getAccessToken();
            logger.info("获取的token值为:" + token);

            /**3、获取凭证ticket发起GET请求 */
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + token;
            logger.info("接口调用凭证ticket的requestUrl：" + requestUrl);

            //JSONObject jsonObject = LYHttpRequestUtil.sendGet(requestUrl,  null);
            String ticktresult = WxCommonUtil.httpsRequestString(requestUrl, "GET", null);
            JSONObject jsonresult = new JSONObject(ticktresult);
            //JSONObject jsonObject = WxCommonUtil.httpsRequest(requestUrl, "GET", null);
            //使用JSSDK支付，需要另一个凭证，也就是jsapi_ticket。这个是JSSDK中使用到的。
            String jsapi_ticket = jsonresult.getString("ticket");
            //JSONObject jsonObject = WxCommonUtil.httpsRequest(requestUrl, "GET", null);
            //使用JSSDK支付，需要另一个凭证，也就是jsapi_ticket。这个是JSSDK中使用到的。
            //String jsapi_ticket = jsonObject.getString("ticket");
            logger.info("jsapi_ticket：" + jsapi_ticket);
            // 获取到ticket凭证之后，需要进行一次签名
            String config_nonceStr = YZRandom.createNoncestr(32);// 获取随机字符串
            long config_timestamp = new Date().getTime();// 时间戳
            // 加入签名的参数有4个，分别是： noncestr、jsapi_ticket、timestamp、url，注意字母全部为小写
            SortedMap<Object, Object> configMap = new TreeMap<Object, Object>();
            configMap.put("noncestr", config_nonceStr);
            configMap.put("jsapi_ticket", jsapi_ticket);
            configMap.put("timestamp", config_timestamp+"");
            configMap.put("url", url);
            String config_sign = WxCommonUtil.createSignSHA1("UTF-8", configMap);
            // 将config_nonceStr、jsapi_ticket 、config_timestamp、config_sign一同传递到前端
            // 这几个参数名称和上面获取预支付prepay_id使用的参数名称是不一样的，不要混淆了。
            // 这几个参数是提供给前端js代码在调用wx.config中进行配置的参数，wx.config里面的signature值就是这个config_sign的值，以此类推
            Map params = new HashMap();
            params.put("config_nonceStr", config_nonceStr);
            params.put("config_timestamp", config_timestamp+"");
            params.put("config_sign", config_sign);
            params.put("app_id", APPID);
            params.put("noncestr", config_nonceStr);
            params.put("jsapi_ticket", jsapi_ticket);
            params.put("timestamp", config_timestamp+"");
            params.put("url", url);
            //该签名是用于前端js中wx.config配置中的signature值。
            // 将map转换为json字符串，传递给前端ajax回调
            String json = new JSONObject(params).toString();
            logger.info("用于wx.config配置的json：" + json);

//            response.setContentType("text/plain");
//            response.setHeader("Cache-Control", "no-cache");
//            response.setCharacterEncoding("UTF-8");
//            try {
//                PrintWriter writer = response.getWriter();
//                writer.print(json);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            return  params;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
